<?php

namespace App\Models\Admin;

use App\Common\ValidateHandler;
use App\Models\BaseModel;
use App\Models\Admin\Menu;

class Rule extends BaseModel
{
    protected $fillable = [
        'id', 'title', 'url', 'menu_id', 'parent_menu_id',
        'created_at', 'updated_at'
    ];

    public function getList($pageSize)
    {
        $data = $this->orderBy('created_at', 'desc')->paginate($pageSize)->toArray();
        $data = $this->handleData($data);

        return $this->success($data);
    }

    private function handleData($data)
    {
        foreach ($data['data'] as $key => &$item) {
            $item['menu_name'] = Menu::where('id', $item['menu_id'])->first()->title;
        }

        return $data;
    }

    public function handle($data)
    {
        $result = $this->validate($data);
        if(!$result['res']) return $result;

        if ($data['id'] == 'new') {
            unset($data['id']);
            $this->create($data);
        } else {
            $id = $data['id'];
            $this->where('id', $id)->update($data);
        }

        return $this->success(['res' => true, 'info' => '操作成功']);
    }

    private function validate($data){
        $arr = [
            0 => [
                'name' => '权限名称',
                'value' => $data['title'],
                'func' => 'is_empty'
            ],
            2 => [
                'name' => '接口地址',
                'value' => $data['url'],
                'func' => 'is_empty'
            ]
        ];
        if ($data['parent_menu_id'] == 0) return ['res' => false, 'info' => '请选择主菜单'];
        if ($data['menu_id'] == 0) return ['res' => false, 'info' => '请选择子菜单'];

        return ValidateHandler::do($arr);
    }

    public function deleteAction($id)
    {
        //如果权限被角色使用，不可删除
        $roleCount = Role::where("rule_ids", "like", "$id,%")
                          ->orWhere("rule_ids", "like", "%,$id,%")
                          ->count();
        if ($roleCount > 0) {
            return $this->error(['info' => '请删除此权限对应的角色后再来删除']);
        }

        $this->find($id)->delete();
        return $this->success(['info' => '操作成功']);
    }
}
